package com.itheima.review.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.model.review.pojos.Review;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 审核结果监听器
 * 监听来自 task-service 的审核结果，更新书评状态
 */
@Component
@Slf4j
public class AuditResultListener {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 监听审核结果
     * 消息格式：
     * {
     *   "taskId": "uuid",
     *   "contentType": "review",
     *   "contentId": "reviewId",
     *   "userId": 1001,
     *   "auditStatus": 3,
     *   "suggestion": "PASS/BLOCK",
     *   "label": "违规类型",
     *   "confidence": 0.95,
     *   "timestamp": 1698765432000
     * }
     */
    @KafkaListener(topics = "audit-result", groupId = "review-service")
    public void handleAuditResult(String message) {
        try {
            log.info("收到审核结果: {}", message);

            JSONObject result = JSON.parseObject(message);
            String contentType = result.getString("contentType");

            // 只处理书评类型的审核结果
            if (!"review".equals(contentType)) {
                log.debug("非书评类型审核结果，跳过: contentType={}", contentType);
                return;
            }

            String contentId = result.getString("contentId");
            String suggestion = result.getString("suggestion");
            String label = result.getString("label");

            // 根据审核结果更新书评状态
            Integer reviewStatus;
            if ("PASS".equals(suggestion)) {
                reviewStatus = Review.APPROVED;  // 1-通过
                log.info("书评审核通过: reviewId={}", contentId);
            } else {
                reviewStatus = Review.REJECTED;  // 2-拒绝
                log.warn("书评审核拒绝: reviewId={}, label={}", contentId, label);
            }

            // 更新 MongoDB
            updateReviewStatus(contentId, reviewStatus, label);

            log.info("更新书评状态成功: reviewId={}, status={}, label={}", 
                    contentId, reviewStatus, label);

        } catch (Exception e) {
            log.error("处理审核结果失败: message={}", message, e);
        }
    }

    /**
     * 更新书评状态
     */
    private void updateReviewStatus(String reviewId, Integer status, String auditLabel) {
        try {
            Query query = new Query(Criteria.where("_id").is(reviewId));
            Update update = new Update()
                    .set("status", status)
                    .set("update_time", new Date());

            // 如果有审核标签，也记录下来（可选）
            if (auditLabel != null && !"正常内容".equals(auditLabel)) {
                update.set("audit_label", auditLabel);
            }

            mongoTemplate.updateFirst(query, update, Review.class);

            // TODO: 如果审核不通过，可以发送站内消息通知用户
            if (Review.REJECTED.equals(status)) {
                // sendNotificationToUser(reviewId, auditLabel);
            }

        } catch (Exception e) {
            log.error("更新书评状态失败: reviewId={}, status={}", reviewId, status, e);
            throw e;
        }
    }
}

